package parse.xml;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


/**
 * 
 * @author cjcj
 *
 */
public class XMLParser {
	public Document parser(InputStream is) throws ParserConfigurationException, SAXException, IOException{
		DocumentBuilderFactory f=DocumentBuilderFactory.newInstance();
		DocumentBuilder builder=f.newDocumentBuilder();
		Document doc=builder.parse(is);
		getItems(doc.getDocumentElement());
		return doc;
	}
	
	private Map<String,String> getItems(Element n){
		if(n==null)throw new NullPointerException();
		// get the item..
		NodeList nl=n.getElementsByTagName("item");
		for(int i=0;nl!=null&&i<nl.getLength();++i){
			Element et=(Element) nl.item(i);
			System.out.println(getTextValue(et,"title"));
			System.out.println(getTextValue(et,"URL"));
			System.out.println(getTextValue(et,"pubDate"));
		}
		return null;
		
	}
	
	private String getTextValue(Element e,String tagNm){
		NodeList nl=e.getElementsByTagName(tagNm);
		return nl!=null&&nl.getLength()>0?nl.item(0).getFirstChild().getNodeValue():null;
	}
}

